package com.chart.common.utils.sms;



import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.core.redis.RedisCache;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author tianyh
 * @Description:普通短信发送
 */
public class SmsSendUtils {

    public static final String qcode = "手机号：";

    public static final String charset = "utf-8";
    // 用户平台API账号(非登录账号,示例:N1234567)
    public static String account = "N2515324";
    // 用户平台API密码(非登录密码)
    public static String password = "0JxzcSwDF2fa24";

    public static AjaxResult sendSms(String phoneNum, RedisCache redisCache) throws UnsupportedEncodingException {
        //请求地址请登录253云通讯自助通平台查看或者询问您的商务负责人获取
        String smsSingleRequestServerUrl = "https://smssh1.253.com/msg/v1/send/json";
        // 短信内容
        String code = getCode();
        String msg = "【TOPCHARTS】尊敬的用户，您的验证码为"+code+"，3分钟内有效，请不要把验证码泄露给他人";
        //状态报告
        String report= "true";

        SmsSendRequest smsSingleRequest = new SmsSendRequest(account, password, msg, phoneNum,report);

        String requestJson = JSON.toJSONString(smsSingleRequest);

//        System.out.println("before request string is: " + requestJson);

        String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, requestJson);

//        System.out.println("response after request result is :" + response);

        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

//        System.out.println("response  toString is :" + smsSingleResponse);
        if (smsSingleResponse.getCode().equals("0")) {
            redisCache.setCacheObject(qcode+phoneNum,code,3, TimeUnit.MINUTES);
            return AjaxResult.success(code);
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        String errorMsg = JSON.toJSONString(jsonObject.get("errorMsg"));
        return AjaxResult.error(errorMsg);
    }

    public static String getCode() {
        Random random = new Random();
        int min = 100000; // 最小值为100000
        int max = 999999; // 最大值为999999
        int randomNumber = random.nextInt(max - min + 1) + min;
        return String.valueOf(randomNumber);
    }
}
